<?php

if_get('/element_instances', function ()
{/*{{{*/
    list(
        $inputs['element_id'], $inputs['event_instance_id']
    ) = input_list(
        'element_id', 'event_instance_id'
    );

    $inputs = array_filter($inputs, 'not_null');

    $element_instances = dao('element_instance')->find_all_by_column($inputs);

    return [
        'count' => count($element_instances),
        'element_instances' => array_build($element_instances, function ($id, $element_instance) {
            return [
                null,
                [
                    'id' => $element_instance->id,
                    'element_display' => $element_instance->element->display_for_element_instances_element(),
                    'event_instance_display' => $element_instance->event_instance->display_for_element_instances_event_instance(),
                    'create_time' => $element_instance->create_time,
                    'update_time' => $element_instance->update_time,
                ]
            ];
        }),
    ];
});/*}}}*/

if_post('/element_instances/add', function ()
{/*{{{*/

    $element_instance = element_instance::create(
        input_entity('element', null, 'element_id'),
        input_entity('event_instance', null, 'event_instance_id')
    );

    return [
        'id' => $element_instance->id,
    ];
});/*}}}*/

//todo::detail

if_post('/element_instances/update/*', function ($element_instance_id)
{/*{{{*/

    $element_instance = dao('element_instance')->find($element_instance_id);
    otherwise_error_code('ELEMENT_INSTANCE_NOT_FOUND', $element_instance->is_not_null());

    $element_instance->element = input_entity('element', null, 'element_id');
    $element_instance->event_instance = input_entity('event_instance', null, 'event_instance_id');

    return true;
});/*}}}*/

if_post('/element_instances/delete/*', function ($element_instance_id)
{/*{{{*/
    $element_instance = dao('element_instance')->find($element_instance_id);
    otherwise_error_code('ELEMENT_INSTANCE_NOT_FOUND', $element_instance->is_not_null());

    $element_instance->delete();

    return true;
});/*}}}*/
